<?php

namespace backend\controllers;

use backend\models\AuthAssignment;
use backend\models\AuthItem;
use backend\models\AuthItemChild;
use Exception;
use Yii;
use backend\models\Backenduser;
use yii\data\ActiveDataProvider;
use yii\rbac\Item;
use yii\web\Controller;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use backend\models\SignupForm;
use yii\web\Response;
use yii\widgets\ActiveForm;

/**
 * BackenduserController implements the CRUD actions for BackendUser model.
 */
class BackenduserController extends BaseController
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'maxLength' => 4,
                'minLength' => 4,
            ],
        ];
    }

    /**
     *删除角色
     */
    public function actionDelJiaose($id)
    {
        AuthItem::deleteAll(['name'=>$id,'type'=>1])?
            Yii::$app->getSession()->setFlash('success', '删除成功'):
            Yii::$app->getSession()->setFlash('error', '删除出错');
        return $this->redirect(['quanxian']);
    }

    /**
     *编辑角色
     */
    public function actionUpJiaose($id)
    {
        $jiaose = AuthItem::findOne($id);
        $authitem = Yii::$app->request->post('AuthItem');
        if (!empty($authitem)){
            if($jiaose->validate($authitem)){
                $jiaose->name = $authitem['name'];
                $jiaose->description = $authitem['description'];
                $jiaose->updated_at = time();
                $jiaose->save()? Yii::$app->getSession()->setFlash('success', '角色编辑成功'):
                    Yii::$app->getSession()->setFlash('error', '角色编辑失败');
                return $this->redirect(['quanxian']);
            }
            else{
                throw new \yii\web\UnauthorizedHttpException('天，失败了');
            }
        }

        return $this->render('createjiaose',['jiaose'=>$jiaose,'isNewRecord'=>false]);
    }

    /**
     * @创建角色
     */
    public function actionCreateJiaose(){
        $jiaose = new AuthItem();
        $authitem = Yii::$app->request->post('AuthItem');
        if (!empty($authitem)){
           if($jiaose->validate($authitem)){
                $jiaose->name = $authitem['name'];
                $jiaose->description = $authitem['description'];
                $jiaose->type = 1;
                $jiaose->created_at = $jiaose->updated_at = time();
                $jiaose->save()?
                    Yii::$app->getSession()->setFlash('success', '添加成功'):
                    Yii::$app->getSession()->setFlash('error', '添加失败');
               return $this->redirect(['quanxian']);
           }
           else{
               throw new \yii\web\UnauthorizedHttpException('天，失败了');
            }

        }


        return $this->render('createjiaose',['jiaose'=>$jiaose,'isNewRecord'=>true]);
    }

    /**
     * @分配角色权限
     */
    public function actionUpPermission(){

        $permission = Yii::$app->request->post('permission');

        if (!empty($permission)){
            $backend_user = Yii::$app->request->post('id');
            try{
                AuthItemChild::deleteAll(['parent'=>$backend_user]);
                foreach ($permission as $v){
                        $aic1 = new AuthItemChild();
                        $aic1->parent = $backend_user;
                        $aic1->child = $v;

                       if($aic1->save())
                           Yii::$app->getSession()->setFlash('success', Backenduser::getJiaoSe().'权限修改成功');
                }
            }catch (Exception $e){
                throw new \yii\web\UnauthorizedHttpException($e);
            }

        }

        $permissions = AuthItem::find()->where('type=2')->asArray()->all();
//        $user = AuthItemChild::findOne(['user_id'=>Yii::$app->request->get('id')]);
        $aic = AuthItemChild::find()->where('parent=:user',[':user'=>Yii::$app->request->get('id')])->asArray()->all();
        $checkper = [];
        foreach ($aic as $k=>$v){
            $checkper[] = $v['child'];
        }

        foreach (Yii::$app->params['permission'] as $k=>$v){
            foreach ($v['child'] as $ck=>$cv) {
                foreach ($permissions as $pv) {
                    if (strpos($pv['name'], $ck)) {
                        $permissiongroup[$k][$ck][$pv['name']] = $pv['description'];
                    }

                }
                if (empty($permissiongroup[$k][$ck]))
                    $permissiongroup[$k][$ck][] = '';

                foreach ($cv['child'] as $cck=>$ccv) {
                    foreach ($permissions as $pv) {
                        if (strpos($pv['name'], $cck)) {
                            $permissiongroup[$k][$cck][$pv['name']] = $pv['description'];
                        }
                    }
                    if (empty($permissiongroup[$k][$cck]))
                        $permissiongroup[$k][$cck][] = '';

                }

            }
        }
//        echo '<pre>'; echo print_r($checkper);exit();
        return $this->render('uppermission',['permissiongroup'=>$permissiongroup,
            'permission'=>Yii::$app->params['permission'],'checkper'=>$checkper]);
    }

    /**
     * @后台角色页面
     */
    public function actionQuanxian(){
        $date =AuthItem::findOne(['name'=>'admin']);
//        echo '<pre>'; echo ($date->authString[0]->child);exit();
        $dataProvider = new ActiveDataProvider([
            'query' => AuthItem::find()->where('type=1')
        ]);
        return $this->render('quanxian',['dataProvider'=>$dataProvider,'date'=>$date]);
    }

    /**
     * @分配角色
     */
    public function actionFenpei()
    {
        $fenpei = Yii::$app->request->post('fenpei');
        if (isset($fenpei)){
            AuthAssignment::deleteAll('user_id=:id',[':id'=>Yii::$app->request->post('id')]);
//            foreach ($fenpei as $v){

                $ass = new AuthAssignment();
                $ass->item_name = $fenpei;
                $ass->user_id = Yii::$app->request->post('id').'';
                $ass->created_at = time();
                if($ass->save())
                     Yii::$app->getSession()->setFlash('success', '修改角色成功');
                else
                    Yii::$app->getSession()->setFlash('error', '坏了');

//            }
        }

        $itemdata = AuthItem::find()->select('name,description')->where('type=1')->asArray()->all();
        foreach ($itemdata as $v){
            $item[$v['name']] = $v['description'];
        }
        $assignmentdata = AuthAssignment::find()->select('item_name')->where('user_id='.Yii::$app->request->get('id'))->asArray()->all();
        foreach ($assignmentdata as $k=> $v){
            $assignmentdata[$k] = $v['item_name'];
        }
//    echo '<pre>'; echo print_r($assignmentdata);exit();
        return $this->render('fenpei',['itemdata'=>$item,'assignmentdata'=>$assignmentdata]);
    }


    /**
     * Lists all BackendUser models.
     * @return mixed
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Backenduser::find(),
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single BackendUser model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new BackendUser model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new SignupForm();

        if ($model->load(Yii::$app->request->post()) ) {
            if ($user = $model->signup()) {
                return $this->redirect(['index']);
            }
        } else {
            return $this->render('create', [
                'model' => $model,

            ]);
        }
    }

    /**
     * Updates an existing BackendUser model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing BackendUser model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the BackendUser model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Backenduser the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Backenduser::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
